/**
 * 材料清单输入组件
 */
import React, { useState } from 'react';
import { Plus, X } from 'lucide-react';

interface MaterialsInputProps {
  value: string[];
  onChange: (materials: string[]) => void;
  className?: string;
}

const MaterialsInput: React.FC<MaterialsInputProps> = ({ value, onChange, className = '' }) => {
  const [newMaterial, setNewMaterial] = useState('');

  const handleAddMaterial = () => {
    if (newMaterial.trim()) {
      onChange([...value, newMaterial.trim()]);
      setNewMaterial('');
    }
  };

  const handleRemoveMaterial = (index: number) => {
    onChange(value.filter((_, i) => i !== index));
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleAddMaterial();
    }
  };

  return (
    <div className={`space-y-2 ${className}`}>
      <div className="flex gap-2">
        <input
          type="text"
          value={newMaterial}
          onChange={(e) => setNewMaterial(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder="输入材料项并按回车添加"
          className="flex-1 px-3 py-2 text-sm border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-ring"
        />
        <button
          type="button"
          onClick={handleAddMaterial}
          className="px-3 py-2 bg-primary text-primary-foreground text-sm rounded-md hover:bg-primary/90 transition-colors"
        >
          <Plus className="h-4 w-4" />
        </button>
      </div>

      <div className="flex flex-wrap gap-2">
        {value.map((material, index) => (
          <div
            key={index}
            className="flex items-center gap-1 px-2 py-1 bg-secondary text-secondary-foreground rounded-md text-sm"
          >
            <span>{material}</span>
            <button
              type="button"
              onClick={() => handleRemoveMaterial(index)}
              className="p-1 hover:text-destructive transition-colors"
            >
              <X className="h-3 w-3" />
            </button>
          </div>
        ))}
      </div>
    </div>
  );
};

export default MaterialsInput;
